﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.IO;
using System.Net;
using System.Text;
using System.Web.Services.Description;

namespace CSharpHelpers.Nets
{
    class WebServiceHelper
    {
        private CompilerResults cr;
        private Type type;

        public WebServiceHelper(string url)
        {
            Init(url, null);
        }

        public WebServiceHelper(string url, string classname)
        {
            Init(url, classname);
        }

        private void Init(string url, string classname)
        {
            if (String.IsNullOrEmpty(classname))
            {
                classname = WebServiceHelper.GetClassName(url);
            }

            ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();

            //获取服务描述语言(WSDL)
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead(url + "?WSDL");
            sdi.AddServiceDescription(ServiceDescription.Read(stream), "", "");

            //生成客户端代理类代码
            CodeNamespace cn = new CodeNamespace(null);
            CodeCompileUnit ccu = new CodeCompileUnit();
            ccu.Namespaces.Add(cn);
            sdi.Import(cn, ccu);

            //设定编译器的参数
            CompilerParameters cpParams = new CompilerParameters();
            cpParams.GenerateExecutable = false;
            cpParams.GenerateInMemory = true;
            cpParams.ReferencedAssemblies.Add("System.dll");
            cpParams.ReferencedAssemblies.Add("System.XML.dll");
            cpParams.ReferencedAssemblies.Add("System.Web.Services.dll");
            cpParams.ReferencedAssemblies.Add("System.Data.dll");

            //编译代理类
            CodeDomProvider cdp = CodeDomProvider.CreateProvider("CSharp");
            cr = cdp.CompileAssemblyFromDom(cpParams, ccu);

            if (true == cr.Errors.HasErrors)
            {
                System.Text.StringBuilder sb = new StringBuilder();
                foreach (CompilerError ce in cr.Errors)
                {
                    sb.Append(ce.ToString());
                    sb.Append(System.Environment.NewLine);
                }
            }

            //生成代理实例,并调用方法
            System.Reflection.Assembly assembly = cr.CompiledAssembly;
            type = assembly.GetType("." + classname, true, true);
        }

        /// <summary>
        /// url="http://localhost/InvokeService/Service1.asmx", return "Service1"
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static string GetClassName(string url)
        {
            string[] parts = url.Split('/');
            string[] pps = parts[parts.Length - 1].Split('.');
            return pps[0];
        }

        /// <summary>
        /// 动态调用WebService
        /// </summary>
        /// <param name="methodname">方法名(模块名)</param>
        /// <param name="args">参数列表</param>
        /// <returns>object</returns>
        public object InvokeWebService(string methodname, params object[] args)
        {
            object obj = Activator.CreateInstance(type);
            System.Reflection.MethodInfo mi = type.GetMethod(methodname);
            return mi.Invoke(obj, args);
        }
    }
}
